package com.by;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Productor {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建连接工厂   创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("erp");//虚拟主机 默认是 /
        factory.setPort(5672); //连接端口号
        factory.setHost("192.168.203.130");//服务器地址 默认是localhost
        factory.setUsername("admin");
        factory.setPassword("123456");

        //2.创建连接  资源自动释放（连接、信道 关闭）
        try (Connection conn = factory.newConnection(); Channel channel = conn.createChannel()) {

            //3.启用发布确认
            channel.confirmSelect();

            //4.接收服务器确认的消息
            channel.addConfirmListener((deliveryTag, multiple) -> {
                System.out.println("服务器确认消息：" + deliveryTag);
            }, (deliveryTag, multiple) -> {
                System.out.println("服务器没有收到消息：" + deliveryTag);
            });

            //4.声明队列
            String queueName = "confirm-single";
            channel.queueDeclare(queueName, false, false, false, null);

            //5.发布消息
            // channel.basicPublish("", queueName, null, "发布确认".getBytes());
            //6. 等待服务器返回结果 或者超时
            // channel.waitForConfirmsOrDie(5000);

            long beign = System.currentTimeMillis();

            for (int i = 1; i <= 1000; i++) {
                channel.basicPublish("", queueName, null, ("消息" + i).getBytes());
                channel.waitForConfirmsOrDie(5000);
            }
            System.out.println("耗费时间:"+(System.currentTimeMillis()-beign));

            System.out.println("消息发布完毕，服务器已收到");
        }

    }
}